package com.ingenio.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import com.ingenio.business.Producto;
import com.ingenio.business.Proveedor;
import com.ingenio.dao.ProductoAdapter;
import com.ingenio.dao.ProveedorAdapter;

/**
 * Servlet implementation class BuscarProductos
 */
@WebServlet("/BuscarProductos")
public class BuscarProductos extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BuscarProductos() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			
			String descripcion = request.getParameter("descripcion");
			String categoria = request.getParameter("categoria");
			String id_rubro = request.getParameter("rubro");
			String id_subrubro = request.getParameter("subRubro");
			String id_marca = request.getParameter("marca");
			String id_proveedor = request.getParameter("codProveedor");
			Proveedor proveedor = null;
			
			if(id_proveedor != null) {
				Integer idProveedor = Integer.parseInt(id_proveedor);
				ProveedorAdapter proveedorAdapter = new ProveedorAdapter();
				proveedor = proveedorAdapter.devolverProveedor(idProveedor);
			}
			
			if( descripcion != null || categoria != null || id_rubro != null || id_subrubro != null || id_marca != null){
				ProductoAdapter pa = new ProductoAdapter();
				List<Producto> productos = pa.buscarProductos(descripcion, id_marca, id_rubro, id_subrubro, categoria, proveedor);
				JSONObject json = new JSONObject();
				JSONArray ja = new JSONArray();
				
				for (Producto p : productos) {
				   JSONObject jo = new JSONObject();
				   jo.put("id", p.getIdProducto());
				   jo.put("desc", p.getDescProducto());
				   ja.put(jo);
				}
				json.put("products", ja);
				response.setContentType("application/json");
				response.getWriter().write(json.toString());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
